import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'

import EventEmitter from '@/http/eventEmitter'

const routes: Array<RouteRecordRaw> = [
  {
    //路由初始指向
    path: '/',
    name: 'home',

    component: () => import('@/pages/home/index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/login/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 注册订阅者事件
EventEmitter.on('APP:UN_AUTH', () => {
  router.push('/login')
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') {
    return '/login'
  }
  next()
})

export default router
